const { devDebug } = require("../settings");
import { order_state_map } from './db_data'

async function search(searchText, searchData) {
  console.log('搜索字段：' + searchText);
  const resList = await new Promise(resolve => {
    wx.cloud.callFunction({
      name: 'db_order',
      data: {
        funcName: 'query',
        searchText: searchText,
        searchData: searchData,
      },
      success: (r) => resolve(r.result),
    });
  })
  if (devDebug) console.log('订单搜索结果', resList);
  return resList.map(o => {
    o.created_time = new Date(o.created_time).Format()
    o.modified_time = new Date(o.modified_time).Format()
    o.payment_time = o.payment_time ? new Date(o.payment_time).Format() : ''
    o.payment_price = '¥' + (o.payment_price.toFixed(2));
    o.order_state = order_state_map.get(o.order_state)
    o.court_name = o.courts.length > 2
      ? `${o.courts[0].court_name}等共计${o.courts.length}个场`
      : o.courts.map(o => o.court_name).join('，');
    return o;
  })
}

async function viewOrder(orderId) {
  wx.navigateTo({
    url: `/pages/user/order/detail?orderId=${orderId}&adminView=1`,
  })
}

module.exports = {
  title: '_id',
  subtitle: 'order_state',
  data_keys: [
    { k: 'stadium_name', v: '预订球馆' },
    { k: 'court_name', v: '预订场地' },
    { k: 'real_name', v: '真实姓名' },
    { k: 'payment_price', v: '支付金额' },
    { k: 'created_time', v: '创建时间' },
    { k: 'payment_time', v: '支付时间' },
  ],
  data_btns: [
    { label: '订单详情', funcName: 'viewOrder' },
  ],
  search_placeholder: '搜索球馆名称或用户名',
  header_btn: { text: '导出订单', url: '/pages/templates/404?errMsg=暂未实现' },
  tabs: [
    { label: '全部', searchData: {} },
    { label: '待支付', searchData: { order_state: 0 } },
    { label: '待使用', searchData: { order_state: 2 } },
    { label: '交易关闭', searchData: { order_state: 1 } },
    { label: '交易完成', searchData: { order_state: 3 } },
  ],
  viewOrder,
  search,
}